package vn.lumi.smarthome.ui.schedule;

import java.util.Calendar;

import net.margaritov.preference.colorpicker.ColorPickerDialog;
import net.margaritov.preference.colorpicker.ColorPickerDialog.OnColorChangedListener;
import net.margaritov.preference.colorpicker.ColorPickerDialog.OnTouchReleasedListener;
import net.margaritov.preference.colorpicker.ColorPickerPanelView;
import net.margaritov.preference.colorpicker.ColorPickerView;
import vn.lumi.smarthome.Config;
import vn.lumi.smarthome.LumiHome;
import vn.lumi.smarthome.R;
import vn.lumi.smarthome.io.database.TBL_Schedule;
import vn.lumi.smarthome.io.model.Device;
import vn.lumi.smarthome.io.model.Schedule;
import vn.lumi.smarthome.io.model.Time;
import vn.lumi.smarthome.service.VibrateThread;
import vn.lumi.smarthome.ui.base.BaseFragment;
import vn.lumi.smarthome.ui.base.ButtonCustom;
import vn.lumi.smarthome.ui.base.TextViewCustom;
import vn.lumi.smarthome.ui.scene.AbstractSceneFragment;
import vn.lumi.smarthome.ulti.ChangeFont;
import vn.lumi.smarthome.ulti.Preference;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.ToggleButton;

public class AddScheduleFragment extends BaseFragment implements
		OnClickListener {

	public static final String EXTRA_DEVICE_ID = "device id";
	public static final String EXTRA_DEVICE_NAME = "device name";
	public static final String EXTRA_DEVICE_TYPE = "device type";
	public static final String EXTRA_COLOR = "color";
	public static final String ADDSCHEDULEFRAGMENT = "addScheduleFragment";

	private int deviceId;
	private String deviceName;
	private int deviceType;

	private TextView txvDescription;
	private TextView txvSave;
	private FrameLayout frameRGB;
	private ColorPickerPanelView colorPickerPanel;
	private ColorPickerDialog mColorPickerDialog;
	private ColorPickerView mColorPickerView;
	private ImageView imv_rgb;

	// Hieuph modify
	protected TextView tvPickertimeOn;
	protected ImageView imv_picker_time_on;
	protected TextView tvPickertimeOff;
	protected ImageView imv_picker_time_off;
	protected ToggleButton tgbScheduleOn;
	protected ToggleButton tgbScheduleOff;
	private ListView lsv_schedule;
	MyAdapter myApdater;
	private Button btnBack;

	private boolean mT2 = false;
	private boolean mT3 = false;
	private boolean mT4 = false;
	private boolean mT5 = false;
	private boolean mT6 = false;
	private boolean mT7 = false;
	private boolean mCn = false;
	private int color;
	ProgressDialog dialog;
	// ====================================
	private int mTurnOnHour;
	private int mTurnOnMinute;
	private int mTurnOffHour;
	private int mTurnOffMinute;

	public static AddScheduleFragment newInstance(int devId, String devName,
			int devType, int color) {
		AddScheduleFragment addScheduleFragment = new AddScheduleFragment();
		Bundle bundle = new Bundle();
		bundle.putInt(EXTRA_DEVICE_ID, devId);
		bundle.putString(EXTRA_DEVICE_NAME, devName);
		bundle.putInt(EXTRA_DEVICE_TYPE, devType);
		bundle.putInt(EXTRA_COLOR, color);
		addScheduleFragment.setArguments(bundle);
		return addScheduleFragment;
	}

	public void refresh(int devId, String devName, int devType, int color) {
		deviceId = devId;
		deviceName = devName;
		deviceType = devType;
		this.color = color;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.activity_schedule_base_new,
				container, false);
		init_view(view);
		setupActionbar(view);
		return view;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Config.configLanguage(getActivity().getBaseContext(),
				Preference.getLanguage(getActivity().getApplicationContext()));// Thiet lap ngon ngu
		deviceId = getArguments().getInt(EXTRA_DEVICE_ID, -1);
		deviceName = getArguments().getString(EXTRA_DEVICE_NAME);
		deviceType = getArguments().getInt(EXTRA_DEVICE_TYPE, -1);
		color = getArguments().getInt(EXTRA_COLOR);
	}

	public int getColor() {
		return color;
	}

	public void setColor(int color) {
		this.color = color;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Config.isVibrate = Preference.getVibrate(getActivity());
	}

	public void finish() {
		// TODO Auto-generated method stub
		if (Config.isVibrate)
			new VibrateThread(getActivity().getApplicationContext()).start();
		FragmentManager fm = getActivity().getSupportFragmentManager();
		fm.popBackStack();
	}

	private void setupActionbar(View view) {
		txvSave = (TextView) view
				.findViewById(R.id.actionbar_setting_activity_logout);
		txvSave.setText(getString(R.string.txt_save));
		txvSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (Config.isVibrate)
					new VibrateThread(getActivity().getApplicationContext())
							.start();
				creatSchedule();
			}
		});
		TextView tvCreatScedule = (TextView) view
				.findViewById(R.id.actionbar_setting_activity_set);
		tvCreatScedule.setText(getString(R.string.txt_creat_schedule));
		btnBack = (Button) view
				.findViewById(R.id.actionbar_setting_activity_back);
		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}

	protected void showColorPickerDialog(
			OnColorChangedListener onColorChangedListener,
			OnTouchReleasedListener onTouchReleasedListener, int value) {
		mColorPickerDialog = new ColorPickerDialog(getActivity(), value);
		mColorPickerView = (ColorPickerView) mColorPickerDialog
				.findViewById(R.id.color_picker_view);
		mColorPickerView.setOnColorChangedListener(mColorPickerDialog);
		mColorPickerDialog.setOnColorChangedListener(onColorChangedListener);
		mColorPickerDialog.setOnTouchReleasedListener(onTouchReleasedListener);
		mColorPickerDialog.setCancelable(false);
		mColorPickerDialog.show();
	}

	public void creatSchedule() {
		boolean repeat = false;
		// Hieuph modify

		boolean[] days = new boolean[7];
		days[0] = getT2();
		days[1] = getT3();
		days[2] = getT4();
		days[3] = getT5();
		days[4] = getT6();
		days[5] = getT7();
		days[6] = getCn();

		if (getT2() || getT3() || getT4() || getT5() || getT6() || getT7()
				|| getCn())
			repeat = true;
		else {
			repeat = false;
		}
		// ---------------

		if (!tgbScheduleOff.isChecked()) {
			mTurnOffHour = Schedule.SCHEDULE_NOT_TURNOFF_TYPE;
			mTurnOffMinute = Schedule.SCHEDULE_NOT_TURNOFF_TYPE;
		}

		if (!tgbScheduleOn.isChecked()) {
			mTurnOnHour = Schedule.SCHEDULE_NOT_TURNON_TYPE;
			mTurnOnMinute = Schedule.SCHEDULE_NOT_TURNON_TYPE;
		} else {
			// day la truong hop bat ngay thiet bi.Neu bat ngay thiet bi
			// them 1 vao bit cao nhat
			if (mTurnOnHour == getTimeSytem().getHour()
					&& mTurnOnMinute == getTimeSytem().getMinute()) {
				// Them 1 vao bit dau tien cua byte mTurnOnHour
				mTurnOnHour = mTurnOnHour | 128;
			}
		}
		if (tgbScheduleOff.isChecked() || tgbScheduleOn.isChecked()) {

			ContentValues values = new ContentValues();

			values.put("Device Id", deviceId);
			values.put("Repeat", repeat);
			values.put("Monday", days[0]);
			values.put("Tuesday", days[1]);
			values.put("Wednesday", days[2]);
			values.put("Thursday", days[3]);
			values.put("Friday", days[4]);
			values.put("Saturday", days[5]);
			values.put("Sunday", days[6]);
			values.put("Turn on hour", mTurnOnHour);
			values.put("Turn on minute", mTurnOnMinute);
			values.put("Turn off hour", mTurnOffHour);
			values.put("Turn off minute", mTurnOffMinute);

			// Phan nhom cac thiet bi sang tung loai de xu ly
			int deviceLayoutType = Device.getLayoutType(deviceType);
			if (deviceLayoutType == Device.TYPE_LAYOUT_HOR_BLIND
					|| deviceLayoutType == Device.TYPE_LAYOUT_VER_BLIND) {
				byte[] valueBytes = { Device.DEVICE_STATE_BLIND_MAX_LEVEL };
				values.put("Dev_state", valueBytes);
			} else if (deviceLayoutType == Device.TYPE_LAYOUT_DIMMER) {
				byte[] valueBytes = { Device.DEVICE_STATE_DIMMER_ON };
				values.put("Dev_state", valueBytes);
			} else if (deviceLayoutType == Device.TYPE_LAYOUT_RGB) {
				byte[] valueBytes = new byte[3];
				int color = getColor();
				int Blue = color % 256;
				color = color / 256;
				int Green = color % 256;
				color = color / 256;
				int Red = color % 256;
				valueBytes[0] = (byte) Red;
				valueBytes[1] = (byte) Green;
				valueBytes[2] = (byte) Blue;
				values.put("Dev_state", valueBytes);
			} else if (deviceLayoutType == Device.TYPE_LAYOUT_ONOFF) {
				byte[] valueBytes = { Device.DEVICE_STATE_DEVICE_ON };
				values.put("Dev_state", valueBytes);
			}

			getActivity()
					.getApplicationContext()
					.getContentResolver()
					.update(TBL_Schedule.CONTENT_URI_SCHEDULE_ADD, values,
							null, null);

			// show dialog
			this.dialog = new ProgressDialog(new ContextThemeWrapper(
					getActivity(), R.style.AlertDialogCustom));
			this.dialog.setMessage(getString(R.string.txt_saving_scene_in_HC));
			this.dialog.setCancelable(false);
			this.dialog.show();
			// Thay doi font chu cua Dialog
			ChangeFont changeFont = new ChangeFont(getActivity()
					.getApplicationContext());
			TextView textView = (TextView) dialog
					.findViewById(android.R.id.message);
			textView = changeFont.changeFontTextView(textView,
					R.string.txt_saving_scene_in_HC, LumiHome.font, 16,
					Gravity.NO_GRAVITY,
					getResources().getColor(R.color.greenActionbar));

			// set broadcast receiver
			AddScheduleReceiver mReceiver = new AddScheduleReceiver(dialog);
			IntentFilter filter = new IntentFilter();
			filter.addAction(this
					.getString(R.string.txt_broadcast_create_schedule_successful));
			filter.addAction(this
					.getString(R.string.txt_broadcast_create_schedule_failed));
			filter.addAction(this
					.getString(R.string.txt_broadcast_create_schedule_overload));
			getActivity().registerReceiver(mReceiver, filter);
		} else {
			showCustomDialogBoth(R.string.txt_error,
					R.string.txt_have_no_schedule);
		}
	}

	private void init_view(View view) {

		// Hieuph modify

		lsv_schedule = (ListView) view
				.findViewById(R.id.activity_schedule_base_listview);
		myApdater = new MyAdapter();
		lsv_schedule.setAdapter(myApdater);

		tvPickertimeOn = (TextViewCustom) view
				.findViewById(R.id.activity_schedule_base_tv_picker_time_on);
		imv_picker_time_on = (ImageView) view
				.findViewById(R.id.activity_schedule_base_img_picker_time_on);
		imv_picker_time_on.setOnClickListener(this);
		tvPickertimeOff = (TextViewCustom) view
				.findViewById(R.id.activity_schedule_base_tv_picker_time_off);
		imv_picker_time_off = (ImageView) view
				.findViewById(R.id.activity_schedule_base_img_picker_time_off);
		imv_picker_time_off.setOnClickListener(this);
		tgbScheduleOff = (ToggleButton) view
				.findViewById(R.id.activity_schedule_base_tbg_time_turnOff);
		tgbScheduleOn = (ToggleButton) view
				.findViewById(R.id.activity_schedule_base_tbg_time_turnOn);
		if (tgbScheduleOn.isChecked()) {
			tvPickertimeOn.setEnabled(true);
			imv_picker_time_on.setEnabled(true);
			tgbScheduleOn.setBackgroundResource(R.drawable.img_tickon);

		} else {
			tvPickertimeOn.setEnabled(false);
			imv_picker_time_on.setEnabled(false);
			tgbScheduleOn.setBackgroundResource(R.drawable.img_tickoff);
		}
		if (tgbScheduleOff.isChecked()) {
			tvPickertimeOff.setEnabled(true);
			imv_picker_time_off.setEnabled(true);
			tgbScheduleOff.setBackgroundResource(R.drawable.img_tickon);
		} else {
			tvPickertimeOff.setEnabled(false);
			imv_picker_time_off.setEnabled(false);
			tgbScheduleOff.setBackgroundResource(R.drawable.img_tickoff);
		}
		tgbScheduleOn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (Config.isVibrate)
					new VibrateThread(getActivity().getApplicationContext())
							.start();
				if (tgbScheduleOn.isChecked()) {
					tvPickertimeOn.setEnabled(true);
					imv_picker_time_on.setEnabled(true);
					tgbScheduleOn.setBackgroundResource(R.drawable.img_tickon);
					Calendar c = Calendar.getInstance();
					int hour = c.get(Calendar.HOUR_OF_DAY);
					int minute = c.get(Calendar.MINUTE);
					tvPickertimeOn.setText(AbstractSceneFragment
							.padding_str(hour)
							+ ":"
							+ AbstractSceneFragment.padding_str(minute));
					mTurnOnHour = hour;
					mTurnOnMinute = minute;

					// Bat mau cho RGB
					if (deviceType == Device.DEVICE_TYPE_RGB) {
						colorPickerPanel.setColor(color + 0xFF000000);
						imv_rgb.setImageResource(R.drawable.img_rgb);
					}

				} else {
					tvPickertimeOn.setEnabled(false);
					imv_picker_time_on.setEnabled(false);
					tgbScheduleOn.setBackgroundResource(R.drawable.img_tickoff);
					tvPickertimeOn.setText("");

					// Tat mau cho RGB
					if (deviceType == Device.DEVICE_TYPE_RGB) {
						colorPickerPanel.setColor(getResources().getColor(
								R.color.black));
						imv_rgb.setImageResource(R.drawable.img_rgb_black);
					}
				}
			}
		});
		tgbScheduleOff.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (Config.isVibrate)
					new VibrateThread(getActivity().getApplicationContext())
							.start();
				// TODO Auto-generated method stub
				if (tgbScheduleOff.isChecked()) {
					tvPickertimeOff.setEnabled(true);
					imv_picker_time_off.setEnabled(true);
					tgbScheduleOff.setBackgroundResource(R.drawable.img_tickon);
					Calendar c = Calendar.getInstance();
					int hour = c.get(Calendar.HOUR_OF_DAY);
					int minute = c.get(Calendar.MINUTE);
					tvPickertimeOff.setText(AbstractSceneFragment
							.padding_str(hour)
							+ ":"
							+ AbstractSceneFragment.padding_str(minute));
					mTurnOffHour = hour;
					mTurnOffMinute = minute;

				} else {
					tvPickertimeOff.setEnabled(false);
					imv_picker_time_off.setEnabled(false);
					tgbScheduleOff
							.setBackgroundResource(R.drawable.img_tickoff);
					tvPickertimeOff.setText("");
				}
			}
		});
		txvDescription = (TextView) view
				.findViewById(R.id.activity_schedule_base_txv_description);
		txvDescription.setText(getActivity().getApplicationContext().getString(
				R.string.txt_schedule)
				+ deviceName);

		if (deviceType == Device.DEVICE_TYPE_RGB) {
			frameRGB = (FrameLayout) view
					.findViewById(R.id.activity_schedule_base_new_frame_rgb);
			frameRGB.setVisibility(View.VISIBLE);
			colorPickerPanel = (ColorPickerPanelView) view
					.findViewById(R.id.activity_schedule_base_new_rgb_color_panel);
			imv_rgb = (ImageView) view
					.findViewById(R.id.activity_schedule_base_new_rgb);

			if (tgbScheduleOn.isChecked()) {
				imv_rgb.setImageResource(R.drawable.img_rgb);

				// set mau cho ColorPickerPanelView
				colorPickerPanel.setColor(color + 0xFF000000);
			} else {
				imv_rgb.setImageResource(R.drawable.img_rgb_black);

				// set mau cho ColorPickerPanelView
				colorPickerPanel.setColor(getResources()
						.getColor(R.color.black));
			}

			final OnColorChangedListener onColorChangedListener = new OnColorChangedListener() {
				@Override
				public void onColorChanged(int color) {
					// De khi tao lich thi lay ra
					setColor(color);
				}

				@Override
				public void onCancelDialog() {
				}
			};
			final OnTouchReleasedListener onTouchReleasedListener = new OnTouchReleasedListener() {
				@Override
				public void onTouchReleased(int color) {

					colorPickerPanel.setColor(color);
				}
			};

			imv_rgb.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (imv_picker_time_on.isEnabled()) {
						showColorPickerDialog(onColorChangedListener,
								onTouchReleasedListener,
								colorPickerPanel.getColor());
					}
				}
			});

		}

		// ----------------------------------------------
	}

	// ==============================Cac ham ve thu=======================
	public void setT2(boolean isOn) {
		mT2 = isOn;
		Log.e("setT2", "" + isOn);
	}

	public boolean getT2() {
		Log.e("getT2", "" + mT2);
		return mT2;
	}

	public void setT3(boolean isOn) {
		mT3 = isOn;
	}

	public boolean getT3() {
		return mT3;
	}

	public void setT4(boolean isOn) {
		mT4 = isOn;
	}

	public boolean getT4() {
		return mT4;
	}

	public void setT5(boolean isOn) {
		mT5 = isOn;
	}

	public boolean getT5() {
		return mT5;
	}

	public void setT6(boolean isOn) {
		mT6 = isOn;
	}

	public boolean getT6() {
		return mT6;
	}

	public void setT7(boolean isOn) {
		mT7 = isOn;
	}

	public boolean getT7() {
		return mT7;
	}

	public void setCn(boolean isOn) {
		mCn = isOn;
	}

	public boolean getCn() {
		return mCn;
	}

	// -----------------------------------------------------------------------

	public static Time getTimeSytem() {
		Calendar c = Calendar.getInstance();
		Time timeSystem = new Time(c.get(Calendar.HOUR_OF_DAY),
				c.get(Calendar.MINUTE));
		return timeSystem;
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		Calendar c = Calendar.getInstance();
		int hour = c.get(Calendar.HOUR_OF_DAY);
		int minute = c.get(Calendar.MINUTE);
		if (Config.isVibrate)
			new VibrateThread(getActivity().getApplicationContext()).start();
		switch (view.getId()) {
		case R.id.activity_schedule_base_img_picker_time_on:
			// Get Current time System
			TimepickDialog(getActivity().getApplicationContext(), hour, minute,
					true);
			break;
		case R.id.activity_schedule_base_tv_picker_time_on:
			TimepickDialog(getActivity().getApplicationContext(), hour, minute,
					true);
			break;
		case R.id.activity_schedule_base_img_picker_time_off:
			TimepickDialog(getActivity().getApplicationContext(), hour, minute,
					false);
			break;
		case R.id.activity_schedule_base_tv_picker_time_off:
			TimepickDialog(getActivity().getApplicationContext(), hour, minute,
					false);
			break;
		}
	}

	private class MyAdapter extends BaseAdapter {
		private int mSize = 7;

		@Override
		public int getCount() {
			return mSize;
		}

		@Override
		public Object getItem(int arg0) {
			return arg0;
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.BaseAdapter#getViewTypeCount()
		 */
		@Override
		public int getViewTypeCount() {
			// TODO Auto-generated method stub
			return 1;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.BaseAdapter#getItemViewType(int)
		 */
		@Override
		public int getItemViewType(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.BaseAdapter#isEnabled(int)
		 */
		@Override
		public boolean isEnabled(int position) {
			// TODO Auto-generated method stub
			return true;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			if (convertView == null) {
				convertView = View.inflate(getActivity()
						.getApplicationContext(),
						R.layout.item_listview_base_schedule, null);
				ViewHolder viewholder = new ViewHolder();
				viewholder.tv = (TextView) convertView
						.findViewById(R.id.item_listview_base_schedule_tv);
				viewholder.tgb = (ToggleButton) convertView
						.findViewById(R.id.item_listview_base_schedule_check);
				viewholder.linear = (LinearLayout) convertView
						.findViewById(R.id.item_listview_base_schedule_linear);
				convertView.setTag(viewholder);
			}
			final ViewHolder holder = (ViewHolder) convertView.getTag();
			switch (position) {
			case 0:
				holder.tv.setText(getString(R.string.txt_monday_full));
				if (getT2()) {
					holder.tgb.setBackgroundResource(R.drawable.img_tickon);
					Log.e("checkT2", "1:" + position);
				} else {
					holder.tgb.setBackgroundResource(R.drawable.img_tickoff);
					Log.e("checkT2false", "1:" + position);
					Log.e("checkT2false", "1:" + holder.tgb.isChecked());
				}
				break;
			case 1:
				holder.tv.setText(getString(R.string.txt_tuesday_full));
				if (getT3()) {
					holder.tgb.setBackgroundResource(R.drawable.img_tickon);
					Log.e("checkT3", "1:" + position);
				} else {
					holder.tgb.setBackgroundResource(R.drawable.img_tickoff);
					Log.e("checkT3false", "1:" + position);
				}
				break;
			case 2:
				holder.tv.setText(getString(R.string.txt_wenesday_full));
				if (getT4()) {
					holder.tgb.setBackgroundResource(R.drawable.img_tickon);
					Log.e("checkT4", "1:" + position);
				} else {
					holder.tgb.setBackgroundResource(R.drawable.img_tickoff);
					Log.e("checkT4false", "1:" + position);
				}
				break;
			case 3:
				holder.tv.setText(getString(R.string.txt_thursday_full));
				if (getT5()) {
					holder.tgb.setBackgroundResource(R.drawable.img_tickon);
					Log.e("checkT5", "1:" + position);
				} else {
					holder.tgb.setBackgroundResource(R.drawable.img_tickoff);
					Log.e("checkT5false", "1:" + position);
				}
				break;
			case 4:
				holder.tv.setText(getString(R.string.txt_friday_full));
				if (getT6()) {
					holder.tgb.setBackgroundResource(R.drawable.img_tickon);
					Log.e("checkT6", "1:" + position);
				} else {
					holder.tgb.setBackgroundResource(R.drawable.img_tickoff);
					Log.e("checkT6false", "1:" + position);
				}
				break;
			case 5:
				holder.tv.setText(getString(R.string.txt_saturday_full));
				if (getT7()) {
					holder.tgb.setBackgroundResource(R.drawable.img_tickon);
					Log.e("checkT7", "1:" + position);
				} else {
					holder.tgb.setBackgroundResource(R.drawable.img_tickoff);
					Log.e("checkT7false", "1:" + position);
				}
				break;
			case 6:
				holder.tv.setText(getString(R.string.txt_sunday_full));
				if (getCn()) {
					holder.tgb.setBackgroundResource(R.drawable.img_tickon);
					Log.e("checkCn", "1:" + position);
				} else {
					holder.tgb.setBackgroundResource(R.drawable.img_tickoff);
					Log.e("checkCnfalse", "1:" + position);
				}
				break;
			default:
				break;
			}

			holder.tgb
					.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

						@Override
						public void onCheckedChanged(CompoundButton buttonView,
								boolean isChecked) {
							// TODO Auto-generated method stub
							if (Config.isVibrate)
								new VibrateThread(getActivity()
										.getApplicationContext()).start();
							if (isChecked) {
								buttonView
										.setBackgroundResource(R.drawable.img_tickon);
								switch (position) {
								case 0:
									Log.e("checkT2CheckTrue", "1:" + position);
									setT2(true);
									break;
								case 1:
									setT3(true);
									break;
								case 2:
									setT4(true);
									break;
								case 3:
									setT5(true);
									break;
								case 4:
									setT6(true);
									break;
								case 5:
									setT7(true);
									break;
								case 6:
									Log.e("checkCnCheckTrue", "1:" + position);
									setCn(true);
									break;
								}
							} else {
								buttonView
										.setBackgroundResource(R.drawable.img_tickoff);
								switch (position) {
								case 0:
									Log.e("checkT2CheckFalse", "1:" + position);
									setT2(false);
									break;
								case 1:
									setT3(false);
									break;
								case 2:
									setT4(false);
									break;
								case 3:
									setT5(false);
									break;
								case 4:
									setT6(false);
									break;
								case 5:
									setT7(false);
									break;
								case 6:
									Log.e("checkCnCheckFalse", "1:" + position);
									setCn(false);
									break;
								}
							}
						}
					});
			holder.linear.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (Config.isVibrate)
						new VibrateThread(getActivity().getApplicationContext())
								.start();
					// TODO Auto-generated method stub
					switch (position) {
					case 0:
						if (!getT2()) {
							setT2(true);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickon);
						} else {
							setT2(false);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickoff);
						}

						break;
					case 1:
						if (!getT3()) {
							setT3(true);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickon);
						} else {
							setT3(false);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickoff);
						}
						break;
					case 2:
						if (!getT4()) {
							setT4(true);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickon);
						} else {
							setT4(false);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickoff);
						}
						break;
					case 3:
						if (!getT5()) {
							setT5(true);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickon);
						} else {
							setT5(false);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickoff);
						}
						break;
					case 4:
						if (!getT6()) {
							setT6(true);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickon);
						} else {
							setT6(false);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickoff);
						}
						break;
					case 5:
						if (!getT7()) {
							setT7(true);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickon);
						} else {
							setT7(false);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickoff);
						}
						break;
					case 6:
						if (!getCn()) {
							setCn(true);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickon);
						} else {
							setCn(false);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickoff);
						}
						break;
					}
				}
			});

			return convertView;
		}

	}

	public static class ViewHolder {
		public LinearLayout linear;
		public TextView tv;
		public ToggleButton tgb;
	}

	public class AddScheduleReceiver extends BroadcastReceiver {

		private ProgressDialog mDialog;

		public AddScheduleReceiver(ProgressDialog dialog) {
			mDialog = dialog;
		}

		@Override
		public void onReceive(Context context, Intent intent) {
			mDialog.cancel();
			getActivity().unregisterReceiver(this);
			if (intent.getAction() == context
					.getString(R.string.txt_broadcast_create_schedule_successful))
				finish();

			else if (intent.getAction() == context
					.getString(R.string.txt_broadcast_create_schedule_failed))
				showCustomDialog(R.string.txt_error,
						R.string.txt_error_cannot_connect_HC);
			else if (intent.getAction() == context
					.getString(R.string.txt_broadcast_create_schedule_overload)) {

				showCustomDialog(R.string.txt_error,
						R.string.txt_error_overload_schedule_HC);
			}

		}

	}

	private void TimepickDialog(Context cons, int curHours, int curMinutes,
			final boolean isOn) {
		View view = getActivity().getLayoutInflater().inflate(
				R.layout.dialog_wheeltime, null);

		// hours wheel
		final TimePicker timePicker = (TimePicker) view
				.findViewById(R.id.timePicker);
		timePicker.setIs24HourView(true);

		final Button save = (ButtonCustom) view
				.findViewById(R.id.dialog_wheeltime_save);
		final Button cancel = (ButtonCustom) view
				.findViewById(R.id.dialog_wheeltime_cancel);

		AlertDialog.Builder alert = new AlertDialog.Builder(
				new ContextThemeWrapper(getActivity(),
						R.style.AlertDialogCustom));
		TextView title = new TextView(getActivity());
		ChangeFont fontTitle = new ChangeFont(getActivity()
				.getApplicationContext());
		title = fontTitle.changeFontTextView(title, R.string.txt_picker_time,
				LumiHome.font, LumiHome.sizeTittle, Gravity.CENTER,
				getResources().getColor(R.color.green));
		alert.setCustomTitle(title);

		alert.setView(view);
		alert.setCancelable(false);

		final AlertDialog dialog = alert.create();
		dialog.show();

		save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (Config.isVibrate)
					new VibrateThread(getActivity().getApplicationContext())
							.start();
				// TODO Auto-generated method stub
				if (isOn) {
					mTurnOnHour = timePicker.getCurrentHour();
					mTurnOnMinute = timePicker.getCurrentMinute();
					tvPickertimeOn.setText(AbstractSceneFragment
							.padding_str(mTurnOnHour)
							+ ":"
							+ AbstractSceneFragment.padding_str(mTurnOnMinute));

				}

				else {
					mTurnOffHour = timePicker.getCurrentHour();
					mTurnOffMinute = timePicker.getCurrentMinute();
					tvPickertimeOff.setText(AbstractSceneFragment
							.padding_str(mTurnOffHour)
							+ ":"
							+ AbstractSceneFragment.padding_str(mTurnOffMinute));
				}
				dialog.cancel();
				return;
			}
		});
		cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (Config.isVibrate)
					new VibrateThread(getActivity().getApplicationContext())
							.start();
				// TODO Auto-generated method stub
				dialog.cancel();
				return;
			}
		});

		// set time
		timePicker.setCurrentHour(curHours);
		timePicker.setCurrentMinute(curMinutes);

	}

	public void showCustomDialog(int title, int message) {
		AlertDialog.Builder ErrorDialog = new AlertDialog.Builder(
				new ContextThemeWrapper(getActivity(),
						R.style.AlertDialogCustom));

		ChangeFont changeFont = new ChangeFont(getActivity()
				.getApplicationContext());
		TextView tvTitle = new TextView(getActivity().getApplicationContext());
		tvTitle = changeFont.changeFontTextView(tvTitle, title,
				LumiHome.fontBold, LumiHome.sizeTittle, Gravity.CENTER,
				getResources().getColor(R.color.green));
		ErrorDialog.setCustomTitle(tvTitle);
		ErrorDialog.setMessage(message);
		ErrorDialog.setNegativeButton(R.string.glb_txt_return,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (Config.isVibrate)
							new VibrateThread(getActivity()
									.getApplicationContext()).start();
						dialog.cancel();
					}
				});
		AlertDialog alertErrorDialog = ErrorDialog.create();
		alertErrorDialog.show();
		alertErrorDialog.getWindow().getAttributes();
		TextView tvMessage = (TextView) alertErrorDialog
				.findViewById(android.R.id.message);
		tvMessage = changeFont.changeFontTextView(tvMessage, message,
				LumiHome.font, LumiHome.sizeContent, Gravity.NO_GRAVITY,
				getResources().getColor(R.color.greenLight));

		Button btn1 = alertErrorDialog
				.getButton(DialogInterface.BUTTON_NEGATIVE);
		btn1.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),
				LumiHome.fontBold));
		btn1.setTextColor(getResources().getColor(R.color.greenActionbar));
		btn1.setTextSize(LumiHome.sizeButton);
	}

	public void showCustomDialogBoth(int title, int message) {
		AlertDialog.Builder ErrorDialog = new AlertDialog.Builder(
				new ContextThemeWrapper(getActivity(),
						R.style.AlertDialogCustom));

		ChangeFont changeFont = new ChangeFont(getActivity()
				.getApplicationContext());
		TextView tvTitle = new TextView(getActivity().getApplicationContext());
		tvTitle = changeFont.changeFontTextView(tvTitle, title,
				LumiHome.fontBold, LumiHome.sizeTittle, Gravity.CENTER,
				getResources().getColor(R.color.green));
		ErrorDialog.setCustomTitle(tvTitle);
		ErrorDialog.setMessage(message);
		ErrorDialog.setNegativeButton(R.string.glb_txt_return,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						if (Config.isVibrate)
							new VibrateThread(getActivity()
									.getApplicationContext()).start();
						dialog.cancel();

					}
				});
		AlertDialog alertErrorDialog = ErrorDialog.create();
		alertErrorDialog.show();
		alertErrorDialog.getWindow().getAttributes();
		TextView tvMessage = (TextView) alertErrorDialog
				.findViewById(android.R.id.message);
		tvMessage = changeFont.changeFontTextView(tvMessage, message,
				LumiHome.font, LumiHome.sizeContent, Gravity.NO_GRAVITY,
				getResources().getColor(R.color.greenLight));

		Button btn1 = alertErrorDialog
				.getButton(DialogInterface.BUTTON_NEGATIVE);
		btn1.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),
				LumiHome.fontBold));
		btn1.setTextColor(getResources().getColor(R.color.greenActionbar));
		btn1.setTextSize(LumiHome.sizeButton);

	}
}
